package com.pan.download3.ctrl;

import com.pan.entity.ThreadTask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这个是用来控制线程阻塞的
 */
public class BlockCtrl {
    private List<ThreadTask> threadTaskList;

    private ReentrantLock reentrantLock;

    public BlockCtrl() {
        reentrantLock = new ReentrantLock();
        this.threadTaskList = new ArrayList<>();
    }

    /**
     * 阻塞起来
     * @param threadTask
     */
    public void block(ThreadTask threadTask){
        reentrantLock.lock();
        threadTaskList.add(threadTask);
        reentrantLock.unlock();
        LockSupport.park();
    }


    /**
     * 根据章节唤醒线程
     * @param nextNumber
     */
    public void wakeUp(int nextNumber){
        reentrantLock.lock();
        for (int i = 0; i < threadTaskList.size(); i++) {
            if (threadTaskList.get(i).getChapter().getOrderNumber() == nextNumber){
                LockSupport.unpark(threadTaskList.get(i).getThread());
                threadTaskList.remove(i);
                reentrantLock.unlock();
                return;
            }
        }
        reentrantLock.unlock();
    }

}
